'use strict';

/* Filters */

angular.module('myApp.filters', []).
    filter('starContact', ['$rootScope','$sce',function ($rootScope) {
        return function (items) {
        	var usernames = $rootScope.usernames;
            angular.forEach(items,function(item){
            	if(usernames.contains(item.username)) {
            		item.star = true;
            		$rootScope.starContacts.push(item);
                }else {
                	item.star = false;
                }
    		});
            return items;
        };
    }]).filter('searchContacts', function(){
        return function(contacts, condition){
            var newContacts = [];
            var nameInChinese = null;
            var name = null;
            if(condition == null || condition == ''){
                return [];
            }
            condition = condition.toLocaleLowerCase();
            //search in contacts
            angular.forEach(contacts, function (contact) {
                if(!contact.name || !contact.pinyin){
                    return;//continue
                }
                nameInChinese = contact.name.toLocaleLowerCase();
                name = contact.pinyin.toLocaleLowerCase();
                if(nameInChinese.indexOf(condition) > -1 || name.indexOf(condition) > -1){
                    newContacts.push(contact);
                }
            });
            return newContacts;
        }
    }).filter('fullTextSearch', function (OrganizationHandler, ContactHandler) {
        return function (contacts, groups, condition) {
            if(condition == null || condition == ''){
                return [];
            }
            var searchResult = {};
            var searchContacts = [];
            var searchContactIds = [];
            var searchGroups = [];
            var searchGroupIds = [];
            var nameInChinese = null;
            var name = null;
            condition = condition.toLocaleLowerCase();
            //search in contacts
            angular.forEach(angular.copy(contacts), function (contact) {
                if(!contact.name || !contact.pinyin){
                    return;//continue
                }
                nameInChinese = contact.name.toLocaleLowerCase();
                name = contact.pinyin.toLocaleLowerCase();
                if(nameInChinese.indexOf(condition) > -1 || name.indexOf(condition) > -1){
                    searchContacts.push(contact);
                    searchContactIds.push(contact.identifier);
                }
            });
            //search contacts by dept
            var deptMap = {};
            angular.forEach(OrganizationHandler.getOrganizations(), function(org){
                if(!org.name){
                    return;
                }
                if(org.name.indexOf(condition) > -1){
                    deptMap[org.identifier] = org.name;
                }
            });
            angular.forEach(contacts, function(contact){
                var deptIds = contact.deptIds;
                var matchDeptId = null;
                angular.forEach(deptIds, function(deptId){
                    if(deptMap[deptId] != null){
                        matchDeptId = deptId;
                    }
                });
                if(matchDeptId != null){
                    if(!searchContactIds.contains(contact.identifier)){
                        var temp = angular.copy(contact);
                        temp.desc = '部门:'.concat(deptMap[matchDeptId]);//调整部门需要修改
                        searchContacts.push(temp);
                        searchContactIds.push(temp.identifier);
                    }
                }
            });

            //search in groups
            angular.forEach(angular.copy(groups), function(group){
                if(group.invalid || !group.name){
                    return;
                }
                nameInChinese = group.name.toLocaleLowerCase();
                if(nameInChinese.indexOf(condition) > -1){
                    searchGroups.push(group);
                    searchGroupIds.push(group.identifier);
                }
            });
            //search group by contactName
            //暂时注释
            /*
            angular.forEach(groups, function(group) {
                if (searchGroupIds.contains(group.identifier)) {
                    return;
                }
                ContactHandler.getContactsByGroupPromise(group.identifier, true).then(function(groupContacts){
                    angular.forEach(groupContacts, function(contact){
                        if(contact.name == null){
                            return;
                        }
                        if(contact.name.indexOf(condition) > -1){
                            var temp = angular.copy(group);
                            temp.desc = '群成员:'.concat(contact.name);
                            searchGroups.push(temp);
                            searchGroupIds.push(temp.identifier);
                            return;
                        }
                    });
                });
            });
            */
            searchResult['contacts'] = searchContacts;
            searchResult['groups'] = searchGroups;
            return searchResult;
        };
    }).filter('to_trusted', function ($sce) {
        return function (text) {
            return $sce.trustAsHtml('<pre style="white-space:pre-wrap">'.concat(text).concat('</pre>'));
        };
    }).
    filter('toArray', function () {
        return function (obj) {
            if (!(obj instanceof Object)) return obj;
            var arr = [];
            for (var key in obj) {
                arr.push(obj[key]);
            }
            return arr;
        }
    }).
    filter('toContacts', ['DataStore', function (DataStore) {
            return function(groupPersons){
                return DataStore.getContactsByUsernames(groupPersons);
            }
        }
    ]).
    filter('getContactStatus', function () {
        return function(contacts, existedContactIderfiers, checkedContactIderfiers){
            var currentDate = new Date().getTime();
            var newContacts = [];
            angular.forEach(contacts, function(contact){
                if(existedContactIderfiers){
                    contact.isExist = existedContactIderfiers.contains(contact.identifier);
                }
                if(checkedContactIderfiers){
                    contact.isChecked = checkedContactIderfiers.contains(contact.identifier);
                }
                newContacts.push(contact);
            });
            return newContacts;
        }
    }).
    filter('dateFormat', function () {
        return function(date){
            if(date == null){
                return;
            }
            date = new Date(date);
            if(new Date().Format('yyyy/MM/dd') == date.Format('yyyy/MM/dd')){
                return date.Format('hh:mm');
            }else{
                return date.Format('yyyy/MM/dd hh:mm');
            }
        }
    }).
    filter('betyFormat', function () {
    	return function(byte){
    		if(byte<1024){
    			return byte+'k';
    		}
    		var kb = byte/1024;
    		var mb = byte/1024/1024;
    		var gb = byte/1024/1024/1024;
    		if(kb < 1024){
    			byte=kb;
    			return  byte.toFixed(2)+'KB';
    		}else if(mb<1024){
    			byte = mb;
    			return byte.toFixed(2)+'MB';
    		}else{
    			byte = gb;
    			return byte.toFixed(2)+'GB';
    		}
    	};
    }).
    filter('messageSupplementary', ['$rootScope', 'ContactHandler', function ($rootScope, ContactHandler) {
        return function(messages){
            var systemMessageTime = 0;
            angular.forEach(messages, function(message){
                if(ContactHandler.getContact(message.from) == null){
                    return;
                }
                message.fromName = ContactHandler.getContact(message.from).name;
                if(message.msgType){//聊天消息
                    if(messages.indexOf(message) == 0){
                        systemMessageTime = message.timestamp;
                        message.showMessageTime = true;
                    }else{//消息时间 间隔6分钟
                        if((message.timestamp - systemMessageTime)/1000/60 > 6){
                            message.showMessageTime = true;
                            systemMessageTime = message.timestamp;
                        }
                    }
                }
            });
            return messages;
        }
    }]).
    filter('chatMessage', function () {
        return function(messages){
            var chatMessages = [];
            angular.forEach(messages, function(message){
                if(message.msgType){
                    chatMessages.push(message);
                }
            });
            return chatMessages;
        }
    }).
    filter('commandMessage', function () {
        return function(messages){
            var commandMessages = [];
            angular.forEach(messages, function(message){
                if(message.commType && [52,53].contains(message.commType)){
                    commandMessages.push(message);
                }
            });
            return commandMessages;
        }
    }).filter('getContactName', ['ContactHandler', function (ContactHandler) {
        return function(identifier){
            return ContactHandler.getContact(identifier).name;
        }
    }]).filter('getContactNames', ['ContactHandler', function (ContactHandler) {
        return function(identifiers){
            var contactNames = '';
            var index = 0;
            angular.forEach(identifiers, function(identifier){
                index++;
                contactNames += ContactHandler.getContact(identifier).name;
                if(index < identifiers.length){
                    contactNames += ',';
                }
            });
            return contactNames;
        }
    }]).filter('getCompanies', function(){
        return function(organizations){
            var companies = [];
            angular.forEach(organizations,function(org){
                if(org.superior == 0){
                    companies.push(org);
                }
            });
            return companies;
        }
    }).filter('getDepts', function(){
        return function(organizations, companyId){
            var depts = [];
            angular.forEach(organizations,function(org){
                if(org.superior == companyId){
                    depts.push(org);
                }
            });
            return depts;
        }
    }).filter('getContactsByDeptId', function(){
        return function(contacts, deptId){
            var deptContacts = [];
            angular.forEach(contacts,function(contact){
                if(contact.deptIds != null && contact.deptIds.contains(deptId)){
                    deptContacts.push(contact);
                }
            });
            return deptContacts;
        }
    }).filter('filterInvalid', function(){
        return function(groups){
            var newGroups = [];
            angular.forEach(groups, function(group){
               if(group.invalid){
                   return;
               }
               newGroups.push(group);
            });
            return newGroups;
        }
    }).filter('avatarFormat', function(){
        return function(avatar){
            return window.pcWeb.apiAddress + '/api/service/' + avatar + '&access_token=' + window.pcWeb.user.access_token;
        }
    }).filter('editAvatarFormat', function(){
        return function(avatar){
            if(avatar.indexOf('base64') > -1){
                return avatar;
            }
            return window.pcWeb.apiAddress + '/api/service/' + avatar + '&access_token=' + window.pcWeb.user.access_token;
        }
    }).filter('imgUrlFormat', function(){
        return function(imgUrl){
            return window.pcWeb.apiAddress + '/api/service/file/download/' + imgUrl + '?access_token=' + window.pcWeb.user.access_token;
        }
    }).filter('groupUserCountFormat', function(){
        return function(userCount){
            return userCount < 0 ? 0 : userCount;
        }
    });

